package com.dpwgc.demo.interceptor;

import com.alibaba.fastjson.JSON;
import com.dpwgc.demo.mapper.LogMapper;
import com.dpwgc.demo.model.Log;
import com.dpwgc.demo.utils.DateUtil;
import com.dpwgc.demo.utils.RedisUtil;
import com.dpwgc.demo.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.util.Enumeration;
import java.util.HashMap;


/**
 * 登录验证拦截
 */
@Controller
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    LogMapper logMapper;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        //表示接受任意域名的请求,也可以指定域名
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
        //该字段可选，是个布尔值，表示是否可以携带cookie
        response.setHeader("Access-Control-Allow-Credentials", "true");
        //允许跨域的请求方法
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
        //请求头信息
        response.setHeader("Access-Control-Allow-Headers", "*");

        //获取访问者请求的接口路径记录
        String logUri = request.getRequestURI();

        /**
         * 如果是文件上传请求
         */
        if(logUri.equals("/Upload/uploadFile")){

            //获取请求参数的key
            Enumeration<String> keyMap = request.getParameterNames();
            HashMap<String, String> param = new HashMap<String, String>();
            //枚举key，获取请求参数的value
            while (keyMap.hasMoreElements()) {
                String key = keyMap.nextElement();
                String value = request.getParameter(key);
                //添加请求参数
                param.put(key, value);
            }

            //如果上传信息不完整
            if(param.get("fileRename") == null || param.get("url") == null){
                //跳过
                return true;
            }

            DateUtil dateUtil = new DateUtil();

            Log log = new Log();

            log.setLogUri(logUri);//获取访问者请求的接口路径记录
            log.setUserIp(request.getRemoteAddr());//获取访问者的IP地址
            log.setServerIp(InetAddress.getLocalHost().getHostAddress());//获取存储服务器IP地址
            log.setLogTime(dateUtil.getDateTime());//获取访问时间
            log.setUploadFileName(param.get("fileRename"));//获取上传文件名
            log.setUploadFilePath(param.get("url"));//获取上传文件的保存路径

            //插入访问日志记录
            logMapper.insert(log);

            return true;
        }

        /**
         * 其他请求
         */
        else {
            /**
             * 确认管理员权限
             * 请求头部：两个参数
             * @param id 用户id
             * @param token 登录令牌
             */
            String id = request.getHeader("id");//用户id
            String token = request.getHeader("token");//token令牌

            ResultUtil resultUtil = new ResultUtil();

            //如果请求头部id/token值为空
            if (id == null || token == null || id.length()<=0 || token.length()<=6){

                resultUtil.setMsg("请登陆后访问");
                resultUtil.setCode(440);
                response.setCharacterEncoding("UTF-8");
                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(resultUtil));
                writer.flush();
                return false;
            }

            //从redis中取出对应token令牌，进行匹配
            Object resToken = redisUtil.get(id);
            String strToken = String.valueOf(resToken);

            //匹配token令牌
            if (strToken.equals(token)){

                //匹配成功
                return true;

            }else {
                resultUtil.setMsg("请登陆后访问");
                resultUtil.setCode(440);
                response.setCharacterEncoding("UTF-8");
                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(resultUtil));
                writer.flush();
                return false;
            }
        }
    }
}
